<template>
	<view class="htz-signature-body">
		<view class="htz-signature-fixed-top" style="background-color: white; display: flex;flex-direction: column;align-items: center;">
			<view class="" :style="{width: name.length * 15.2 + 'vw',height:15 + 'vw' }" style="display: flex; flex-direction: row; justify-content:center; ">
				<canvas canvas-id="result"  style="width:100%;height: 100%;"></canvas>
			</view>
		</view>
		<view class="htz-signature-fixed-center" style="">
			<view class=""  style="width: 100%;height: 30rpx; line-height: 30rpx; text-align: center;font-size: 30rpx;z-index: 3;">
				{{getTips}}
			</view>
			<view class="">
				<canvas class="signCanvas"  style="position: absolute; /* 绝对定位 */ top: 0; left: 0; z-index: 2;" :canvas-id="cid" :id="cid" @touchstart="touchstart" @touchmove="touchmove" @touchend="touchend"></canvas>
				<canvas class="signCanvas"  style="background-color: white;osition: absolute; /* 绝对定位 */ top: 0; left: 0; z-index: 1;"  canvas-id="background" ></canvas>
			</view>
			<view style="width: 100%;text-align: center;color: gray;height: 30rpx;line-height: 30rpx; font-size: 30rpx">
				{{bottomTips}}
			</view>
		</view>
		
		<view class="htz-signature-fixed-bottom">
			<view class="htz-signature-fixed-bottom-item htz-signature-tools">
				<view class="htz-signature-tools-item" @click="lineWidth">
					<image src="../../../static/images/signature/bicuxi.png"></image>
					<view>线条</view>
				</view>
				<!-- <view class="htz-signature-tools-item" @click="color">
					<image src="../../../static/images/signature/color-plate-fill.png"></image>
					<view>颜色</view>
				</view> -->
				<view class="htz-signature-tools-item" @click="revoke">
					<image src="../../../static/images/signature/chehuinormal.png"></image>
					<view>撤回</view>
				</view>
				<view class="htz-signature-tools-item" @click="clear">
					<image src="../../../static/images/signature/qingkong_1.png"></image>
					<view>清空</view>
				</view>
			</view>
			<view v-if="!(strList[strList.length - 1] && strList[strList.length - 1].image)" class="htz-signature-fixed-bottom-item sumbit" @click="checkSign">提交</view>
			<view v-else class="htz-signature-fixed-bottom-item sumbit" @click="confirm">完成</view>
		</view>
		<view class="htz-signature-color-main" v-if="colorShow">
			<view @click="selColor(index)" :class="index==colorIndex?'htz-signature-color-item on ':'htz-signature-color-item '"
			 :style="'background-color:'+item.value" v-for="(item,index) in colorData" :key="index">
				<image src="../../../static/images/signature/on.png"></image>
			</view>
		</view>
		<view class="htz-signature-color-main" v-if="lineWidthShow">
			<view @click="selLineWidth(index)" :class="index==lineWidthIndex?'htz-signature-lineWidth-item on':'htz-signature-lineWidth-item'"
			 v-for="(item,index) in lineWidthData" :key="index">
				<view :style="'width:60%;height:'+item+'px;background-color:#000000;position: absolute;top: 50%;left: 20%;margin-top:-'+item/2+'px'"></view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		name: 'htz-signature',
		props: {
			cid: {
				type: String,
				default: '',
			},
			bottomTips:{
				type: String,
				default: '',
			},
			name:{
				type: String,
				default: '',
			}
		},
		data() {
			return {
				id: '',
				Strokes: [],
				dom: null,
				width: 0,
				height: 0,
				colorShow: false,
				colorIndex: 0,
				colorData: [{
					name: 'black',
					value: '#000000'
				}, {
					name: 'red',
					value: '#f34336',
				}, {
					name: 'blue',
					value: '#0238d0',
				}, {
					name: 'green',
					value: '#8bc24b',
				}, {
					name: 'yellow',
					value: '#ffeb3c',
				}, {
					name: 'purple',
					value: '#a603d0',
				}, {
					name: 'grey',
					value: '#a5a5a5',
				}],
				lineWidthShow: false,
				lineWidthIndex: 2,
				lineWidthData: ['3', '6', '9', '12', '15', '18'],
				strList:[],
				current:0,
				token:'24.b4f236c8b716b95ebe5efe0a3859cbba.2592000.1703989879.282335-44086521',
				topTips:'请用正楷录入',
				resultCanvas:null,
				background:null,
				errorNum:0
				
			}
		},
		computed:{
			getTips(){
				let _that = this
				if(_that.current >= _that.strList.length && _that.current != 0){
					_that.om.toast("点击‘完成’按钮完成签名")
					return ''
				}
				return _that.topTips +'【'+ (_that.strList[_that.current]?_that.strList[_that.current].text:'') +'】'
			}
		},
		mounted: function() {
			this.$nextTick(function() {
				// #ifdef H5
				document.body.addEventListener('touchmove', this.touchmoveEnd, {
					passive: false
				})
				// #endif
				try {
					let baiduToken = uni.getStorageSync('baiduToken');
					if (baiduToken) {
						this.token = baiduToken
					}
				} catch (e) {
					// error
				}
				uni.getSystemInfo({
					success: (res) => {
						this.width = res.windowWidth;
						this.height = res.windowHeight * 0.7;
					}
				});
				this.dom = uni.createCanvasContext(this.cid, this);
				this.background = uni.createCanvasContext('background', this);
				let sx = 0
				let sy = 0
				let w = this.width
				this.resultCanvas = uni.createCanvasContext('result',this)
				this.background.setFillStyle('white')
				this.background.fillRect(0, 0, this.width,this.width)
				// this.dom.draw()
				let half = w / 2;
				
				//实线
				this.background.strokeStyle = '#FF0000';
				this.background.lineWidth = 1;
				this.background.strokeRect(sx,sy, w - 1, w - 1);
				this.background.save();
				this.background.lineWidth = 1;
				this.background.beginPath();
				this.background.strokeStyle = '#ec8e8e';
				//横线
				this.background.moveTo(sx-1, half+sy);
				this.background.lineTo(w+sx-1, half+sy);
				//竖线
				this.background.moveTo(half+sx, sy);
				this.background.lineTo(half+sx, w+sy);
				this.background.stroke();
				
				//虚线
				this.background.lineWidth = 1;
				this.background.beginPath();
				this.background.setLineDash([5,10]); //创建5像素长，间隔为5像素的虚线
				this.background.strokeStyle = '#ec8e8e';
				//交叉线1
				this.background.moveTo(sx, sy);
				this.background.lineTo(sx+w, sy+w);
				//交叉线2
				this.background.moveTo(sx-1, sy+w);
				this.background.lineTo(sx+w, sy-1);
				this.background.stroke();
				
				this.background.closePath();
				this.background.restore();
				this.background.draw()
				
				
				this.resultCanvas.setFillStyle('white')
				this.resultCanvas.fillRect(0, 0, this.width, this.height)
				this.resultCanvas.draw()
				let strArr = this.name.split('')
				this.name.length
				for(let item of strArr){
					let obj = {
						text:item,
						image:''
					}
					this.strList.push(obj)
				}
			});
		},
		beforeDestroy: function() {
			// #ifdef H5
			document.body.removeEventListener('touchmove', this.touchmoveEnd, {
				passive: false
			})
			// #endif
		},
		methods: {
			initDraw(){
				let _that = this
				_that.dom = uni.createCanvasContext(_that.cid, _that);
				_that.dom.draw()
			},
			captchaSrc(image){
				return image.replace(/[\r\n]/g, "");
			},
				toBase64(path){
				return new Promise((resolve, reject) => {
					// #ifdef APP-PLUS
					plus.io.resolveLocalFileSystemURL(path, (entry) => {
						entry.file((file) => {
							let fileReader = new plus.io.FileReader()
							fileReader.readAsDataURL(file)
							fileReader.onloadend = (evt) => {
								let base64 = evt.target.result.split(",")[1]
								resolve(base64)
							}
						})
					})
					// #endif
					// #ifdef H5
					uni.request({
						url: path,
						responseType: 'arraybuffer',
						success: (res) => {
							resolve(uni.arrayBufferToBase64(res.data))
						}
					})
					// #endif
					// #ifdef MP-WEIXIN
					uni.getFileSystemManager().readFile({
						filePath: path,
						encoding: 'base64',
						success: (res) => {
							resolve(res.data)
						}
					})
					// #endif
				})
			},
			itemClick(index){
				let _that = this
				_that.current = index 
			},
			touchmoveEnd(e) {
				e.preventDefault();
				e.stopPropagation();
			},
			uploadImage(path,image) {
				let _that = this
				uni.showLoading({
					
				})
				uni.request({
					url: 'https://aip.baidubce.com/rest/2.0/ocr/v1/handwriting',
					data: {
						image: path,
						access_token: _that.token
					},
					method: 'POST',
					header: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					success: (res) => {
						uni.hideLoading()
						if(res.data.words_result[0] && res.data.words_result[0].words == _that.strList[_that.current].text){
							_that.$set(_that.strList[_that.current],'image',image)
							_that.resultCanvas.drawImage( _that.strList[_that.current].image,_that.current * _that.width * 0.15,0,_that.width*0.15 ,_that.width*0.15)
							_that.resultCanvas.draw(true)
							if(_that.current < _that.strList.length){
								_that.current++
							}
							_that.errorNum = 0
						}else{
							_that.om.toast('识别失败，请重新录入')
							_that.errorNum ++
						}
						_that.clear()
					}
				})
			},
			confirm(){
				let _that = this
				uni.canvasToTempFilePath({
					canvasId:'result',
					success:(res)=>{
						//#ifdef H5
						_that.$emit('sumbit', res)
						//#endif
						//#ifdef APP-PLUS
						 var savedFilePath = res.tempFilePath;//相对路径
						 var path=plus.io.convertLocalFileSystemURL(savedFilePath);//绝对路径
						 var fileReader = new plus.io.FileReader();
						 fileReader.readAsDataURL(path);
						 fileReader.onloadend = (res) => { //读取文件成功完成的回调函数
						   // console.log(res.target.result) //输出base64内容
							_that.$emit('sumbit',res.target.result)
						 }
						//#endif
					}
				})
			},
			checkSign(){
				let _that = this
				setTimeout(()=>{
				if(_that.Strokes.length>0){
					uni.canvasToTempFilePath({
						canvasId: _that.cid,
						fileType:'jpg',
						success: (res) => {
							//#ifdef H5
							let path = _that.captchaSrc(res.tempFilePath)
							_that.toBase64(res.tempFilePath).then(result=>{
								if(_that.errorNum < 3){
									_that.uploadImage(result,res.tempFilePath)
								}else{
									_that.$set(_that.strList[_that.current],'image',_that.captchaSrc(res.tempFilePath))
									_that.resultCanvas.drawImage( _that.strList[_that.current].image,_that.current * _that.width * 0.15,0,_that.width*0.15 ,_that.width*0.15)
									_that.resultCanvas.draw(true)
									if(_that.current < _that.strList.length){
										_that.current++
									}
									_that.errorNum = 0
									_that.clear()
								}
							})
							//#endif
							//#ifdef APP-PLUS
							 let savedFilePath = res.tempFilePath;//相对路径
							 let path=plus.io.convertLocalFileSystemURL(savedFilePath);//绝对路径
							_that.toBase64(path).then(result=>{
								//正式
								if(_that.errorNum < 3){
									_that.uploadImage(result,path)
									_that.errorNum ++
								}else{
									_that.$set(_that.strList[_that.current],'image',_that.captchaSrc(res.tempFilePath))
									_that.resultCanvas.drawImage( _that.strList[_that.current].image,_that.current * _that.width * 0.15,0,_that.width*0.15 ,_that.width*0.15)
									_that.resultCanvas.draw(true)
									if(_that.current < _that.strList.length){
										_that.current++
									}
									_that.clear()
								}
							})
							//#endif
						},
						fail: (err) => {
							//console.log('fail', err)
							_that.$emit('fail', err)
						}
					}, _that)
				}else{
					_that.om.toast('请先签名')
				}
				},500)
			},
			sumbit() {
				setTimeout(()=>{
				if(this.Strokes.length>0){
					uni.canvasToTempFilePath({
						canvasId: this.cid,
						success: (res) => {
							//#ifdef H5
							this.$emit('sumbit', res)
							//#endif
							//#ifdef APP-PLUS
							 var savedFilePath = res.tempFilePath;//相对路径
							 var path=plus.io.convertLocalFileSystemURL(savedFilePath);//绝对路径
							 var fileReader = new plus.io.FileReader();
							 fileReader.readAsDataURL(path);
							 fileReader.onloadend = (res) => { //读取文件成功完成的回调函数
							   // console.log(res.target.result) //输出base64内容
								this.$emit('sumbit',res.target.result)
							 }
							//#endif
						},
						fail: (err) => {
							//console.log('fail', err)
							this.$emit('fail', err)
						}
					}, this)
				}else{
					this.om.toast('请先签名')
				}
				},500)
				
			},
			clear() { //清空
				let _that = this
				_that.Strokes = [];
				_that.initDraw()
			},
			lineWidth() {
				this.lineWidthShow = !this.lineWidthShow;
				this.colorShow = false;
			},
			selLineWidth(index) {
				this.lineWidthIndex = index;
				this.lineWidthShow = false;
			},
			color() {
				this.colorShow = !this.colorShow;
				this.lineWidthShow = false;
			},
			selColor(index) {
				this.colorIndex = index;
				this.colorShow = false;
			},
			revoke() { //撤销上一步
				var delItem = this.Strokes.pop();
				// if (delItem) {
				// 	delItem.points.forEach((item, index) => {
				// 		if (index < (delItem.points.length - 1)) {
				// 			this.dom.setStrokeStyle('#FFFFFF')
				// 			this.dom.moveTo(delItem.points[index].x, delItem.points[index].y);
				// 			this.dom.lineTo(delItem.points[index + 1].x, delItem.points[index + 1].y);
				// 			this.dom.stroke();
				// 			this.dom.draw(true);
				// 			// this.dom.clearRect(delItem.points[index].x, delItem.points[index].y, 10, 10);
				// 			// this.dom.draw(true)
				// 		}
				// 	})

				// }

				// this.dom.draw();
				// if(this.Strokes.length>0){
				// 	var lastItem = this.Strokes[this.Strokes.length - 1];
				// 	uni.canvasPutImageData({
				// 		canvasId: this.cid,
				// 		data: lastItem.imageData.data,
				// 		x: 0,
				// 		y: 0,
				// 		width: lastItem.imageData.width,
				// 		height: lastItem.imageData.height,
				// 		success:(res)=> {
				// 			console.log('success',res)
				// 		}
				// 	},this)
				// }

				//console.log('delItem', delItem)
				//this.dom.drawImage(delItem.x, delItem.y, 0, 0)
				this.drawCanves();
			},
			drawCanves() {
				//this.dom.draw();
				// this.dom.setFillStyle('white')
				// this.dom.fillRect(0, 0, this.width, this.height)
				this.Strokes.forEach((item, index) => {
					let StrokesItem = item;
					//console.log(index, this.Strokes.length)
					if (StrokesItem.points.length > 1) {
						this.dom.beginPath();
						this.dom.setLineCap('round');
						this.dom.setStrokeStyle(item.style.color);
						this.dom.setLineWidth(item.style.lineWidth);
						StrokesItem.points.forEach((sitem, sindex) => {
							if (sitem.type == "touchstart") {
								this.dom.moveTo(sitem.x, sitem.y)
							} else {
								this.dom.lineTo(sitem.x, sitem.y)
							}
							
							//console.log('dom', sitem)
						})
						this.dom.stroke();
					}
					
				})
				
				this.dom.draw();
			},
			createId() {
				var d = new Date();
				return 'can' + d.getTime();
			},
			touchstart(e) {
				this.Strokes.push({
					imageData: null,
					style: {
						color: this.colorData[this.colorIndex].value,
						lineWidth: this.lineWidthData[this.lineWidthIndex],
					},
					points: [{
						x: e.touches[0].x,
						y: e.touches[0].y,
						type: e.type,
					}]
				})
				this.drawLine(this.Strokes[this.Strokes.length - 1], e.type);
			},
			touchmove(e) {
				this.Strokes[this.Strokes.length - 1].points.push({
					x: e.touches[0].x,
					y: e.touches[0].y,
					type: e.type,
				})
				this.drawLine(this.Strokes[this.Strokes.length - 1], e.type);
			},
			touchend(e) {
				if(this.Strokes[this.Strokes.length - 1].points.length<2){//当此路径只有一个点的时候
					this.Strokes.pop();
				}
				//this.drawLine(this.Strokes[this.Strokes.length - 1], e.type);
				// uni.canvasGetImageData({
				// 	canvasId: this.cid,
				// 	x: 0,
				// 	y: 0,
				// 	width: this.width,
				// 	height: this.height,
				// 	success: (res) => {
				// 		 console.log(res.width) // 100
				// 		// console.log(res.height) // 100
				// 		// console.log(res.data instanceof Uint8ClampedArray) // true
				// 		// console.log(res.data.length) // 100 * 100 * 4
				// 		this.Strokes[this.Strokes.length - 1].imageData = res;
				// 	}
				// },this)
				//this.drawCanves();
			},
			drawLine(StrokesItem, type) {
				if (StrokesItem.points.length > 1) {
					this.dom.setLineCap('round')
					this.dom.setStrokeStyle(StrokesItem.style.color);
					this.dom.setLineWidth(StrokesItem.style.lineWidth);
					this.dom.moveTo(StrokesItem.points[StrokesItem.points.length - 2].x, StrokesItem.points[StrokesItem.points.length -
						2].y);
					this.dom.lineTo(StrokesItem.points[StrokesItem.points.length - 1].x, StrokesItem.points[StrokesItem.points.length -
						1].y);
					this.dom.stroke();
					this.dom.draw(true);
				}
			}
		}
	}
</script>

<style>
	.htz-signature-fixed-center{
		display: flex;
		flex-direction: column;
		justify-content: space-evenly;
		width: 100%; 
		height:80vh;
	}
	.htz-signature-body {
		position: fixed;
		top: 0;
		bottom: 100rpx;
		left: 0;
		width: 100%;
		background-color: #fff;
	}

	.signCanvas {
		width: 100%;
		height: 100vw;
	}
	.htz-signature-fixed-top{
		display: -webkit-flex; /* Safari */
		display: flex;
		justify-content: space-around;
		width: 100%;
		height: 12vh;
		border-bottom: 1px solid #1890ff;
	}
	.htz-signature-fixed-bottom {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		height: 8vh;
		line-height:8vh;
		text-align: center;
		color: #000;
		z-index: 11;
		display: -webkit-box;
		display: -webkit-flex;
		display: flex;
		background-color: #fff;
	}

	.htz-signature-fixed-bottom .htz-signature-fixed-bottom-item {
		-webkit-box-flex: 3;
		-webkit-flex-grow: 3;
		flex-grow: 3;
		border-top: 1px solid #1890ff;
		color: #1890ff;
	}

	.htz-signature-fixed-bottom view.sumbit {
		-webkit-box-flex: 1;
		-webkit-flex-grow: 1;
		flex-grow: 2;
		background-color: #1890ff;
		color: #fff;
	}

	.htz-signature-tools {
		display: -webkit-box;
		display: -webkit-flex;
		display: flex;
		align-items: center;
	}

	.htz-signature-tools-item {
		text-align: center;
		-webkit-box-flex: 1;
		-webkit-flex-grow: 1;
		flex-grow: 1;
		line-height: 35rpx;
		
	}

	.htz-signature-fixed-bottom-item view image {
		width: 50rpx;
		height: 50rpx;
		padding-top: 10rpx;
	}

	.htz-signature-tools-item view {
		font-size: 22rpx;
	}

	.htz-signature-color-main {
		position: fixed;
		bottom: 100rpx;
		left: 0;
		width: 710rpx;
		/* height: 75rpx; */
		z-index: 11;
		padding: 25rpx 20rpx;
		display: -webkit-box;
		display: -webkit-flex;
		display: flex;
		flex-wrap: wrap;
		background-color: #fff;
		border-top: 1px dashed #d9d9d9;
		transition: display 2s;
		-moz-transition: display 2s;
		/* Firefox 4 */
		-webkit-transition: display 2s;
		/* Safari 和 Chrome */
		-o-transition: display 2s;
	}

	.htz-signature-color-item {
		width: 80rpx;
		height: 80rpx;
		background-color: #000000;
		border-radius: 100px;
		margin: 5px;
		position: relative;
	}

	.htz-signature-lineWidth-item {
		width: 80rpx;
		height: 80rpx;
		background-color: #fff;
		border-radius: 100px;
		margin: 5px;
		position: relative;
	}

	.htz-signature-lineWidth-item.on {
		border: 1px solid #d4a39e;
	}

	.htz-signature-color-item image {
		display: none;
	}

	.htz-signature-color-item.on image {
		display: block;
		position: absolute;
		top: 50%;
		left: 50%;
		width: 50rpx;
		height: 50rpx;
		margin-top: -25rpx;
		margin-left: -25rpx;
	}

	.black {
		background-color: #000000 !important;
	}
</style>
